<?php
namespace Common\Model;

class FundNetvalueModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
		array('id', '/^[1-9]\d*$/', '参数错误1', 1, 'regex', 2),
		array('log_note', 'require', '请输入更新日志', 1, 'regex', 2),
		array('fund_id', '/^[1-9]\d*$/', '参数错误2', 1, 'regex', 1),
		array('fund_name', '/^[\w\x{4e00}-\x{9fa5}]{2,}$/u', '参数错误3', 1,'regex', 1),
		array('value', '/^(\d+)|(\d+\.\d*)$/', '净值只能为数值', 1),
		array('netvalue_time', '/^20\d{2}-(0?[1-9]|1[012])-(0?[1-9]|[12]\d|3[01])$/', '日期格式错误，请输入2015-15-10 格式的日期时间', 1),
	);
	
	//自动完成
	protected $_auto = array(
		array('create_time', 'time', 1, 'function'),
		array('update_time', 'time', 3, 'function'),
		array('status', 1, 1, 'string')
	);
	
	/**
	 * 添加净值信息
	 * @author 刘新
	 */
	public function addNetvalue() 
	{
		//创建数据对象
		if($this->create() === false) return array('error' => 1, 'msg' => $this->getError());
		$netValueTime = $this->netvalue_time;
		$this->netvalue_time = strtotime($this->netvalue_time);

		$this->netvalue_hsexcess = ($this->netvalue_hs-1)*100;
		$this->netvalue_cut = ($this->value-$this->netvalue_hs)*100;

		$netValueDate = $this->netvalue_date = date('Y-m-d', $this->netvalue_time);
		$return = array('error' => 0, 'msg' => '添加成功');
		$admin = session('user_auth');

		try {
			//保存
			$res = $this->add();
			if(!$res) throw new \Think\Exception('添加失败');
			
			//更新日志
			$now = time();
			$data['fund_id'] = I('fund_id');
			$data['netvalue_id'] = $res;
			$data['admin_id'] = $admin['uid'];
			$data['admin_name'] = $admin['username'];
			$data['create_time'] = $now;
			$data['update_time'] = $now;
			$data['status'] = 1;
			$data['log_note'] = '添加基金产品“'.I('fund_name').'”，时间为' . $netValueTime . '的基金净值';
			$res = M('FundNetvalueLog')->add($data);
			if(!$res) throw new \Think\Exception('日志添加失败');

			//提交事务
			$this->commit();
		} catch (\Think\Exception $e) {
			$this->rollback();
			$return['error'] = 1;
			$return['msg'] = $e->getMessage();
		}

		return $return;
	}
	
	/**
	 * 编辑净值信息
	 * @author 刘新
	 */
	public function editNetvalue()
	{
		//创建数据对象
		if($this->create() === false) return array('error' => 1, 'msg' => $this->getError());
		$netValueTime = $this->netvalue_time;
		$this->netvalue_time = strtotime($this->netvalue_time);
		$netValueDate = $this->netvalue_date = date('Y-m-d', $this->netvalue_time);
		$return = array('error' => 0, 'msg' => '编辑成功');
		$admin = session('user_auth');
	
		try {
			//保存
			$res = $this->save();
			if(!$res) throw new \Think\Exception('编辑失败');
				
			//更新日志
			$now = time();
			$data['fund_id'] = I('fund_id');
			$data['netvalue_id'] = I('id');
			$data['admin_id'] = $admin['uid'];
			$data['admin_name'] = $admin['username'];
			$data['create_time'] = $now;
			$data['update_time'] = $now;
			$data['status'] = 1;
			$data['log_note'] = I('log_note');
			$res = M('FundNetvalueLog')->add($data);
			if(!$res) throw new \Think\Exception('日志添加失败');
				
			//提交事务
			$this->commit();
		} catch (\Think\Exception $e) {
			$this->rollback();
			$return['error'] = 1;
			$return['msg'] = $e->getMessage();
		}
	
		return $return;
	}
	
	/**
	 * 计算净值
	 * @param int|string $id
	 * @param int|string $type -1-从成立至今的净值，0-今年净值，1-近一月净值，3-近三月净值，6-近6月净值，12-近一年净值；
	 * @param int|string $endDate 以该日期为基准进行计算，可以是时间戳，也可以是yyyy-mm-dd格式的日期字符串；
	 * @return array|boolean 计算成功返回数组，键名为$type，键值为计算结果；计算失败返回false；
	 * @author 刘新
	 */
	public function netvalueCalculate($id, $type, $endDate)
	{
		
	}
	
	/**
	 * 净值计算汇总
	 * @return array 计算成功返回数组，-1-从成立至今的净值，0-今年净值，1-近一月净值，3-近三月净值，6-近6月净值，12-近一年净值；
	 * @author 刘新
	 */
	public function netvalue($id, $endDate) 
	{
		
	}
	
	/**
	 * 获取前一天的基金净值
	 * @author 刘新
	 */
	public function previous($fundId)
	{
		if(!$fundId) return array('error' => 1, 'info' => '参数错误');
		
		//TODO:获取前一天的日期
		$where['netvalue_date'] = date('Y-m-d', strtotime('-1 day', NOW_TIME));
		$where['status'] = 1;
		$netvalue = $this->netvalueInterval($where);
		
		if($netvalue['error'] === 0) {
			$netvalue['info'] = $netvalue['info'][0];
		}
		return $netvalue;
	}
	
	/**
	 * 查询指定日期的基金净值
	 * @author 刘新
	 */
	public function netvalueByDate($date)
	{
		if(is_int($date)) {
			$date = date('Y-m-d', $date);
		} else if(is_string($date)) {
			if(!preg_match('/^2\d{3}-\d{1,2}-\d{1,2}$/')) return array('error' => 1, 'info' => '参数错误');
		} else {
			return array('error' => 1, 'info' => '参数错误');
		}
	
		$where['netvalue_date'] = $date;
		$where['status'] = 1;
		$netvalue = $this->netvalueInterval($where);
	
		if($netvalue['error'] === 0) {
			$netvalue['info'] = $netvalue['info'][0];
		}
		return $netvalue;
	}
	
	private function netvalueInterval($where)
	{
		$netvalue = $this->where($where)->select();
		if($netvalue) return array('error' => 0, 'info' => $netvalue);
		return array('error' => 1, 'info' => '查询失败');
	}
	
	/**
	 * 查询净值
	 * @param number $type
	 */
	public function searchNetvalue($type, $where = array(), $option = array())
	{
		$type = intval($type);
		
		// 普通查询
		if(!$type) {
			$page = 1;
			$size = 5;
			if($option) {
				if($option['page'] && $option['size']) {
					$page = $option['page'];
					$size = $option['size'];
				}
			}
			
			$this->page($page, $size);
			if($where) $this->where($where);
		
		// 为绘净值图准备
		} else {
			// 必需指定要查询的基金产品
			if(!$where || !$where['fund_id']) return false;
			$this->where($where);
			
			//查询近一周净值
			if($type === 1) {
				$count = 5;
			
			//查询近一个月净值
			} else if($type === 2) {
				$count = 20;
			
			//查询成立以来的净值
			} else if($type === 6) {
				$count = false;
			
			//查询成立以来的净值
			} else if($type === 3) {
				$count = 60;
				
			//查询成立以来的净值
			} else if($type === 4) {
				$count = 80;
				
			//查询成立以来的净值
			} else if($type === 5) {
				$count = 100;
			} else {
				return false;
			}
			
			if($count) {
				$this->limit($count);
			}
		}
		
		$value = $this->order('netvalue_date desc')->select();
		
		return $value;
	}
	//获取最新日期的基金信息
	//如果设定了指定日期的话就规定指定日期之后的信息
	public function getnewnetvalue($date = ""){
		//获取所有的基金最新的价格
		if(empty($date)){
			$date = date("Y-m-d");
		}
		$arrwhere['netvalue_date'] = array("elt",$date);
		$fundNetvaluemax = M('FundNetvalue')->where($arrwhere)->group('fund_id')->field('MAX(netvalue_date) AS netvalue_date')->select();
		$maxid = array();
		foreach($fundNetvaluemax as $key=>$val){
			$maxid[] = $val['netvalue_date'];
		}
		$fundNetvaluemaxid = implode(",",$maxid);
		$arrwhere['netvalue_date'] = array("in",$fundNetvaluemaxid);
		$fundNetvalue = M('FundNetvalue')->group('fund_id')->where($arrwhere)->order('netvalue_time desc')->select();
		$nowFundValue = array();
		if(is_array($fundNetvalue)){
			foreach($fundNetvalue as $key=>$val){
				$nowFundValue[$val['fund_id']] = $val['value'];
			}
		}
		return $nowFundValue;
	}

}